using System;
using System.Collections;
using System.Collections.Generic;
using ADougenSDK;
using UnityEngine;
using Newtonsoft.Json;


namespace DemoGame
{
	public class GameConfigManager : Singleton<GameConfigManager>
	{

		public List<Global> GlobalList => getConfig<Global>();

		public List<Sticker> StickerList => getConfig<Sticker>();

		public List<Level> LevelList => getConfig<Level>();

		public List<Shop> ShopList => getConfig<Shop>();

		private List<Global> globalList;

		private List<Sticker> stickerList;

		private List<Level> levelList;

		private List<Shop> shopList;

		private readonly Dictionary<Type, string> typeToEnum = new Dictionary<Type,string> {
			 [typeof(Global)] = "global",
			 [typeof(Sticker)] = "sticker",
			 [typeof(Level)] = "level",
			 [typeof(Shop)] = "shop",
		};

		private void tryLoad(string subModule) 
		{
			 switch (subModule)
			 {
				 case "global": if (globalList != null) return; break;
				 case "sticker": if (stickerList != null) return; break;
				 case "level": if (levelList != null) return; break;
				 case "shop": if (shopList != null) return; break;
				 default: throw new ArgumentOutOfRangeException(nameof(subModule), subModule, null); 
			 }

			 var path = $"Assets/AssetsPackage/JsonConfigs/Game/{subModule}"; 
			 var hander = YooAssetManager.Instance.Package.LoadAssetSync<TextAsset>(path); 
			 var ta = hander.AssetObject as TextAsset; 
			 if (ta == null || string.IsNullOrEmpty(ta.text)) 
			 {
				 LogUtil.LogError($"Load {path} error!"); 
				 return; 
			 }
			 switch (subModule)
			 {
				 case "global" : globalList = JsonConvert.DeserializeObject<List<Global>>(ta.text); break;
				 case "sticker" : stickerList = JsonConvert.DeserializeObject<List<Sticker>>(ta.text); break;
				 case "level" : levelList = JsonConvert.DeserializeObject<List<Level>>(ta.text); break;
				 case "shop" : shopList = JsonConvert.DeserializeObject<List<Shop>>(ta.text); break;
				 default: throw new ArgumentOutOfRangeException(nameof(subModule), subModule, null); 
			 }

		}

		private List<T> getConfig<T>() 
		{
			 var subModule = typeToEnum[typeof(T)]; 
			 tryLoad(subModule); 
			 switch (subModule) 
			 {
				 case "global" : return globalList as List<T>;
				 case "sticker" : return stickerList as List<T>;
				 case "level" : return levelList as List<T>;
				 case "shop" : return shopList as List<T>;
				 default: throw new ArgumentOutOfRangeException(nameof(subModule), subModule, null); 
			 }
		}

	}

}

